package cn.nzcong.jpress.addon.articlesync.interceptor;


import cn.nzcong.jpress.addon.articlesync.annotation.SecondStep;
import cn.nzcong.jpress.addon.articlesync.common.Constant;
import cn.nzcong.jpress.addon.articlesync.common.Exception.InternalServiceException;
import cn.nzcong.jpress.addon.articlesync.common.Exception.SecondStepAuthException;
import cn.nzcong.jpress.addon.articlesync.common.SecondStepAuthHelper;
import cn.nzcong.jpress.addon.articlesync.service.impl.ConfigOptionService;
import cn.nzcong.jpress.addon.articlesync.vo.config.SecondStepConfig;
import com.alibaba.fastjson.JSON;
import com.jfinal.aop.Inject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import io.jboot.utils.RequestUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.Cookie;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;


public class ArticleSyncSecondStepInterceptor implements Interceptor {

    @Inject
    ConfigOptionService configOptionService;

    @Override
    public void intercept(Invocation inv) {

//        System.out.println("ArticleSyncSecondStepInterceptor invoke " + JSON.toJSONString(inv.getMethod().getAnnotation(SecondStep.class)));

        // 未标记@SecondStep的方法，跳过
        if(inv.getMethod().getAnnotation(SecondStep.class) == null){
            inv.invoke();
            return;
        }

        // 查询配置
        SecondStepConfig config = configOptionService.getSecondStepConfig();
        if(config == null || !config.isEnable()){
            // 未设置两步验证，执行后续操作
            inv.invoke();
            return;
        }

        // 两步验证密钥
        String key = config.getKey();
        if(StringUtils.isBlank(key)){
            throw new InternalServiceException("两步验证已启动，但密钥为空");
        }

        // 查询cookie并验证
        try{
            Cookie ssaCookie =  inv.getController().getCookieObject(Constant.SECOND_AUTH_COOKIE_KEY);
            if(ssaCookie == null){
                throw new SecondStepAuthException("无验证信息");
            }
            // 验证cookie内容的有效性
            if(!SecondStepAuthHelper.validCookie(ssaCookie, config.getKey())){
                throw new SecondStepAuthException("验证失败");
            }
            // 验证成功重置cookie时间，一定时间内无相关操作才需要重新验证
            SecondStepAuthHelper.setCookie(inv.getController().getResponse(), config.getKey());
            inv.invoke();
            return;
        } catch (SecondStepAuthException e){
            System.out.println("两步验证失败 - " + e.getMessage());
        }

        String url = inv.getController().getRequest().getRequestURI();
        if(RequestUtil.isAjaxRequest(inv.getController().getRequest())){
            inv.getController().renderJavascript("window.location.href='" + url + "'");
            return;
        }
        // 验证不通过，重定向到验证页面
        try {
            url = "/admin/articlesync/ssa/secondStep?redirect=" + URLEncoder.encode(url, Constant.CHARSET_UTF8);
            inv.getController().getResponse().sendRedirect(url);
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
